package com.fjrz.bbxwj.util

import android.annotation.SuppressLint
import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils

object LocationUtils {
    interface OnSubAdminAreaListener {
        fun onSubAdminArea(adminArea: String?, subAdminArea: String?)
    }

    @SuppressLint("MissingPermission")
    fun location(
        context: Context, onSubAdminAreaListener: OnSubAdminAreaListener
    ) {
        val mLocationManager: LocationManager =
            context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        var mLocation: Location? =
            mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
        if (mLocation == null) {
            mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
        }
        Thread {
            try {
                val mGeocoder = Geocoder(context)
                val addresses: MutableList<Address> = mGeocoder.getFromLocation(
                    (mLocation?.latitude ?: 0.0), (mLocation?.longitude ?: 0.0), (1)
                )
                if (addresses.size != 0) {
                    val address: Address = addresses[0]
                    onSubAdminAreaListener.onSubAdminArea(address.adminArea, address.locality)
                } else {
                    onSubAdminAreaListener.onSubAdminArea(adminArea = null,subAdminArea = null)
                }
            } catch (e: Exception) {
                onSubAdminAreaListener.onSubAdminArea(adminArea = null,subAdminArea = null)
            }
        }.start()
    }
}